#version 130

uniform sampler2D lumaMap;
uniform sampler2D chromaBMap;
uniform sampler2D chromaRMap;

varying vec2 tc_i;

void main()
{
	ivec2 size = textureSize(lumaMap, 0);

	vec2 tc = tc_i * size;

	vec2 w1 = fract(tc);
	vec2 w0 = vec2(1.0) - w1;

	ivec2 tc00 = ivec2(tc.x, tc.y);
	ivec2 tc01 = ivec2(tc00.x + 1,	tc00.y);
	ivec2 tc10 = ivec2(tc00.x,		tc00.y + 1);
	ivec2 tc11 = ivec2(tc00.x + 1,	tc00.y + 1);

	float c00 = texelFetch(lumaMap, tc00, 0).x;
	float c01 = texelFetch(lumaMap, tc01, 0).x;
	float c10 = texelFetch(lumaMap, tc10, 0).x;
	float c11 = texelFetch(lumaMap, tc11, 0).x;

	// binary alpha is stored in the LSB of luma - extract it from all four texels using interval arithmetics
	// alpha = 1 iff luminance belongs to (x - 0.4, x + 0.4), x = 2k + 1, k belongs to Z
	// alpha = 0 otherwise
	float a00 = 1.0 - step(0.2, distance(0.5, fract(c00 * 255.0 * 0.5)));
	float a01 = 1.0 - step(0.2, distance(0.5, fract(c01 * 255.0 * 0.5)));
	float a10 = 1.0 - step(0.2, distance(0.5, fract(c10 * 255.0 * 0.5)));
	float a11 = 1.0 - step(0.2, distance(0.5, fract(c11 * 255.0 * 0.5)));

	float a = 
		w0.x * w0.y * a00 +
		w1.x * w0.y * a01 +
		w0.x * w1.y * a10 +
		w1.x * w1.y * a11;

	float y  = 
		w0.x * w0.y * c00 +
		w1.x * w0.y * c01 +
		w0.x * w1.y * c10 +
		w1.x * w1.y * c11 - 0.5;

	float cb = texture2D(chromaBMap, tc_i).x - 0.5;
	float cr = texture2D(chromaRMap, tc_i).x - 0.5;

	vec3 rgb = vec3(
		y + 1.403 * cr,
		y - 0.344 * cb - 0.714 * cr,
		y + 1.770 * cb);

	gl_FragColor = vec4(rgb + vec3(0.5), a);
}
